<template>
  <div class="chat-container">
    <!-- 欢迎提示 -->
    <div v-if="messages.length === 0" class="welcome-message">
      <div class="message-content">
        我是 AI 助手，有什么可以帮您的？
      </div>
      <div class="message-timestamp">
        {{ new Date().toLocaleTimeString() }}
      </div>
    </div>
    <!-- 消息显示区域 -->
    <div class="message-display" ref="messageDisplay">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="{ 'user-message': msg.isUser, 'ai-message': !msg.isUser }"
          :style="{ animation: `fadeIn 0.5s ease ${index * 0.1}s both` }"
      >
        <div class="message-content">
          {{ msg.content }}
        </div>
        <div class="message-timestamp">
          {{ new Date().toLocaleTimeString() }}
        </div>
      </div>
      <!-- 显示思考中提示 -->
      <div v-if="isThinking" class="ai-message thinking">
        <div class="message-content">
          <span class="dot dot-1">.</span>
          <span class="dot dot-2">.</span>
          <span class="dot dot-3">.</span>
        </div>
      </div>
    </div>
    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <textarea
            v-model="inputMessage"
            placeholder="请输入您的问题，按 Enter 发送，Shift + Enter 换行"
            @keypress="handleKeyPress"
        ></textarea>
        <button @click="sendMessage" :class="{ 'disabled': !(inputMessage.value || '').trim() }">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-send"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';
import OpenAI from 'openai';

// 存储聊天消息的数组，每个消息对象包含内容和发送者标识
const messages = ref([]);
// 用户输入的消息
const inputMessage = ref('');
// 控制 AI 思考中提示的显示
const isThinking = ref(false);

// 初始化 OpenAI 客户端，替换为你的 DeepSeek API 密钥
const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: 'sk-f3364da725a346f88ff79390b094d2c2',
  dangerouslyAllowBrowser: true
});

// 调用 DeepSeek 模型获取回复
const getDeepSeekResponse = async (userMsg) => {
  try {
    const chatMessages = [
      { role: 'system', content: '你是一位专业且友好的 AI 助手，会尽力帮助用户解决问题。' },
      { role: 'user', content: userMsg }
    ];

    const completion = await openai.chat.completions.create({
      messages: chatMessages,
      model: 'deepseek-chat',
    });

    return completion.choices[0].message.content;
  } catch (error) {
    console.error('调用 DeepSeek API 失败:', error);
    throw error;
  }
};

// 发送消息的函数
const sendMessage = async () => {
  const messageContent = (inputMessage.value || '').trim();
  if (!messageContent) return;

  // 添加用户消息到消息列表
  messages.value.push({
    content: messageContent,
    isUser: true
  });

  // 清空输入框
  inputMessage.value = '';

  // 显示思考中提示
  isThinking.value = true;
  await nextTick(); // 等待页面更新
  console.log('思考中提示已显示，isThinking:', isThinking.value);

  try {
    // 调用 DeepSeek 模型获取回复
    const aiResponse = await getDeepSeekResponse(messageContent);
    // 添加 AI 回复到消息列表
    messages.value.push({
      content: aiResponse,
      isUser: false
    });
  } catch (error) {
    console.error('获取 AI 回复失败:', error);
    messages.value.push({
      content: '抱歉，获取 AI 回复失败，请稍后重试。要不您换个问题试试？',
      isUser: false
    });
  } finally {
    // 无论成功与否，隐藏思考中提示
    isThinking.value = false;
    console.log('思考中提示已隐藏，isThinking:', isThinking.value);
  }
};

// 处理回车键发送消息
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};

// 组件挂载时添加初始提示信息
onMounted(() => {
  // 不直接添加到 messages 里，通过模板 v-if 显示欢迎语
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.welcome-message {
  max-width: 70%;
  margin: 24px auto;
  padding: 12px 16px;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
}

.welcome-message .message-content {
  color: #333;
  font-size: 16px;
}

.welcome-message .message-timestamp {
  font-size: 0.8em;
  color: #666;
  margin-top: 4px;
  text-align: right;
  opacity: 0.8;
}

.message-display {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><g fill-rule="evenodd"><g fill="#d9d9d9"><path d="M0 38.59l2.83-2.83 1.41 1.41L1.41 40H0v-1.41zM0 1.4l2.83 2.83 1.41-1.41L1.41 0H0v1.41zM38.59 40l-2.83-2.83 1.41-1.41L40 38.59V40h-1.41zM40 1.41l-2.83 2.83-1.41-1.41L38.59 0H40v1.41zM20 18.6l2.83-2.83 1.41 1.41L21.41 20l2.83 2.83-1.41 1.41L20 21.41l2.83 2.83-1.41 1.41L21.41 20l2.83-2.83-1.41-1.41L20 18.59z"/><path d="M0 19.9l2.83-2.83 1.41 1.41L1.41 20l2.83 2.83-1.41 1.41L0 21.41l-2.83 2.83-1.41-1.41L-1.41 20l-2.83-2.83 1.41-1.41L0 19.9zm40 0l2.83-2.83 1.41 1.41L38.59 20l2.83 2.83-1.41 1.41L40 21.41l2.83 2.83-1.41 1.41L41.41 20l2.83-2.83-1.41-1.41L40 19.9zm-20 0l2.83-2.83 1.41 1.41L18.59 20l2.83 2.83-1.41 1.41L20 21.41l2.83 2.83-1.41 1.41L21.41 20l2.83-2.83-1.41-1.41L20 19.9z"/></g></g></svg>');
  background-size: 40px;
}

.user-message, .ai-message {
  max-width: 70%;
  margin-bottom: 16px;
  position: relative;
  animation-fill-mode: both;
}

.user-message {
  margin-left: auto;
}

.ai-message {
  margin-right: auto;
}

.message-content {
  padding: 12px 16px;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.user-message .message-content {
  background: #dcf8c6;
  color: #333;
}

.ai-message .message-content {
  background: #fff;
  color: #333;
}

.message-timestamp {
  font-size: 0.8em;
  color: #666;
  margin-top: 4px;
  text-align: right;
  opacity: 0.8;
}

.thinking .message-content {
  background: #fff;
  padding: 12px 16px;
  display: flex;
  justify-content: center;
}

.dot {
  width: 6px;
  height: 6px;
  background: #666;
  border-radius: 50%;
  margin: 0 3px;
  animation: bounce 1.2s infinite ease-in-out both;
}

.dot-1 {
  animation-delay: -0.32s;
}

.dot-2 {
  animation-delay: -0.16s;
}

.input-area {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #ddd;
}

.input-wrapper {
  display: flex;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 8px;
}

textarea {
  flex: 1;
  padding: 12px;
  border: none;
  resize: none;
  font-size: 14px;
  outline: none;
}

button {
  background: #075e54;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s ease;
}

button:hover {
  background: #054a42;
}

button.disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>